package com.chenzhou.qx.checklibrary;

import android.content.Context;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.List;

/**
 * Hook WifiManager
 *
 * @author tk
 * @date 2021/1/25
 */
public class HookWifiManager {

    private static final String TAG = "HookWifiManager";

    private static List<String> hookMethodNames = new ArrayList<String>() {{
        add("getConnectionInfo");
    }};

    public static void setHookList(List<String> list) {
        hookMethodNames = list;
    }

    public static void addHooks(String... hookNames) {
        if (hookNames != null && hookNames.length > 0) {
            for (int i = 0; i < hookNames.length; i++) {
                if (!hookMethodNames.contains(hookNames[i])) {
                    hookMethodNames.add(hookNames[i]);
                }
            }
        }
    }

    public static void hookMacAddress(Context context) {
        try {
            Field serviceField = WifiManager.class.getDeclaredField("mService");
            serviceField.setAccessible(true);

            WifiManager wifi = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
            final Object obj = serviceField.get(wifi);
            Class<?> iWifiManager = Class.forName("android.net.wifi.IWifiManager");
            serviceField.set(wifi, Proxy.newProxyInstance(iWifiManager.getClassLoader(),
                    new Class[]{iWifiManager},
                    new InvocationHandler() {
                        @Override
                        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                            if (hookMethodNames.contains(method.getName())) {
                                Log.e(TAG, Log.getStackTraceString(new Throwable()));
                            }
                            return method.invoke(obj, args);
                        }
                    }));
            Log.d(TAG, "hook wifiManager ok");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}